// https://leetcode.cn/problems/number-of-islands/?envType=study-plan-v2&envId=top-interview-150

class Solution {
private:
    int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
public:
    int numIslands(vector<vector<char>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        int ans = 0;
        vector<vector<bool>> visited(m, vector<bool>(n, false));

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1' && !visited[i][j]) {
                    dfs(grid, visited, i, j, m, n);
                    ans++;
                }
            }
        }
        return ans;
    }

    void dfs(vector<vector<char>>& grid, vector<vector<bool>>& visited, int x, int y, int m, int n) {
        if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] != '1' || visited[x][y]) {
            return;
        }

        visited[x][y] = true;
        for (auto dir : dirs) {
            int newX = x + dir[0];
            int newY = y + dir[1];
            dfs(grid, visited, newX, newY, m, n);
        }
    }
};